package cn.test.dubbo.provider;

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.ZkSerializer;
import org.springframework.util.Base64Utils;

import java.io.IOException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

/**
 * @author Han
 */
public class KeyGenerate {
	public static void main(String[] args) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
		ZkClient zkClient = new ZkClient("192.168.100.110:2181,192.168.100.111:2181,192.168.100.112:2181");
		zkClient.setZkSerializer(new ZkSerializer() {
			@Override
			public byte[] serialize(Object data) throws ZkMarshallingError {
				return data.toString().getBytes();
			}

			@Override
			public Object deserialize(byte[] bytes) throws ZkMarshallingError {
				return new String(bytes);
			}
		});


		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

		/** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
//        keyPairGenerator.initialize(KEYSIZE, secureRandom);
		keyPairGenerator.initialize(1024);

		/** 生成密匙对 */
		KeyPair keyPair = keyPairGenerator.generateKeyPair();

		/** 得到公钥 */
		Key publicKey = keyPair.getPublic();

		/** 得到私钥 */
		Key privateKey = keyPair.getPrivate();

		Base64Utils.encodeToString(privateKey.getEncoded());


		zkClient.writeData("/com/dianrong/cfg/1.0.0/uniauth/authentication.jwt.private.key",Base64Utils.encodeToString(privateKey.getEncoded()));


		zkClient.writeData("/com/dianrong/cfg/1.0.0/uniauth/authentication.jwt.public.key",Base64Utils.encodeToString(publicKey.getEncoded()) );
	}
}
